<template>
  <div>
    <el-form
      :model="ruleForm"
      status-icon
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <!-- 输入的表单内容部分 -->
      <el-form-item label="用户名" prop="username">
        <el-input
          type="text"
          v-model="ruleForm.username"
          autocomplete="off"
          required
          placeholder="请输入用户名"
          maxlength="10"
          show-word-limit
        >
        </el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          type="password"
          v-model="ruleForm.password"
          autocomplete="off"
          required
          placeholder="请输入密码"
          show-password
        >
        </el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="checkPass">
        <el-input
          type="password"
          v-model="ruleForm.checkPass"
          autocomplete="off"
          placeholder="请再次输入密码"
          show-password
        ></el-input>
      </el-form-item>
      <!-- 发送邮箱验证码div -->
      <div class="email-item">
        <el-form-item label="电子邮箱" prop="email" style="flex: 0.6 1 auto">
          <el-input
            type="text"
            v-model="ruleForm.email"
            autocomplete="off"
            placeholder="请输入您的电子邮箱(*^▽^*)"
          >
          </el-input>
        </el-form-item>
        <el-button
          :loading="sendEmailLoading"
          :disabled="ruleForm.email.length == '' || disabled"
          style="padding: 0; height: 42px; width: 100px; margin-left: 2px"
          @click="sendEmail"
          >{{ btnText }}</el-button
        >
      </div>
      <!-- 输入验证码 -->
      <div style="display: flex; height: 50px; margin-bottom: 20px">
        <el-form-item label="验证码" prop="emailCaptcha">
          <el-input
            type="text"
            v-model="ruleForm.emailCaptcha"
            autocomplete="off"
            maxlength="5"
            show-word-limit
            placeholder="请输入邮箱验证码"
          >
          </el-input>
        </el-form-item>
      </div>
      <!-- 注册按钮 -->
      <el-form-item>
        <el-button
          type="primary"
          @click="registryUser"
          class="registry-button"
          :disabled="isSendEmail"
        >
          注册</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { uuid } from "vue-uuid";
import UserApiRequest from "@/api/UserApiRequest";
const userApiRequest = new UserApiRequest();
export default {
  name: "registryForm",
  props: {
    showLoginForm: {
      type: Boolean,
      default: false,
    },
    showRegistryForm: {
      type: Boolean,
      default: true,
    },
  },

  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.ruleForm.checkPass !== "") {
          this.$refs.ruleForm.validateField("checkPass");
        }
        callback();
      }
    };
    var validateCode = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入验证码"));
      }
      callback();
    };

    var validateUserName = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入用户名"));
      }
      callback();
    };
    var validatePassAgain = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.ruleForm.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    var validateEmail = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入您的邮箱"));
      }
      callback();
    };
    return {
      // 登录表单信息
      ruleForm: {
        password: "",
        checkPass: "",
        username: "",
        emailCaptcha: "",
        captchaKey: uuid.v1().slice(20),
        email: "",
      },
      // 监控表单属性
      rules: {
        password: [{ validator: validatePass, trigger: "blur" }],
        emailCaptcha: [{ validator: validateCode, trigger: "blur" }],
        username: [{ validator: validateUserName, trigger: "blur" }],
        checkPass: [{ validator: validatePassAgain, target: "blur" }],
        email: [{ validator: validateEmail, target: "blur" }],
      },
      // 验证码计时使用属性
      disabled: false,
      interval: undefined,
      totalCount: 0,
      sendEmailLoading: false,
      isSendEmail: true,
      emailers: "",
    };
  },
  methods: {
    registryUser() {
      let data = {
        username: this.ruleForm.username.trim(),
        password: this.ruleForm.password.trim(),
        emailCaptcha: this.ruleForm.emailCaptcha,
        captchaKey: this.ruleForm.captchaKey,
        email: this.ruleForm.email,
      };
      if (data.username.split(" ").join("").length == 0) {
        this.$message({
          message: "用户名不能为空格哦",
          type: "warning",
        });
        return;
      } else if (data.password.split(" ").join("").length == 0) {
        this.$message({
          message: "密码不能为空格哦",
          type: "warning",
        });
        return;
      } else if (data.password !== this.ruleForm.checkPass) {
        this.$message({
          message: "两次密码不一致",
          type: "warning",
        });
        return;
      } else if (data.email !== this.emailers) {
        this.$message({
          message: "邮箱已修改请重新获取验证码",
          type: "error",
        });
        return;
      }

      userApiRequest.registryUser(data).then((res) => {
        this.checkRegMsg(res);
        if (res.data.code === 203) {
          this.$message({
            message: "恭喜你,注册成功,请进行登录吧!!",
            type: "success",
          });
          // 注册成功后应该回到登录界面 不用关闭窗口
          this.$emit("update:showLoginForm", true);
          this.$refs.ruleForm.resetFields();
          this.$emit("update:showRegistryForm", false);
        }
      });
    },
    // 验证码发送
    sendEmail() {
      // 逻辑判断==> 已发送验证码 与 验证码倒计时60s
      this.isSendEmail = false;
      this.sendEmailLoading = true;
      let data = {
        email: this.ruleForm.email,
        // 验证码key值
        emailKey: this.ruleForm.captchaKey,
        isRegistry: true,
      };
      // 发送验证码
      userApiRequest.getEmailCaptcha(data).then((res) => {
        // 验证码发送状态结果检查
        this.checkSendEmailMsg(res);

        if (res.code === 202) {
          this.sendEmailLoading = false;
          this.$message({
            message: "邮箱发送成功,请登录您的邮箱进行查看",
            type: "success",
          });
          (this.emailers = this.ruleForm.email), (this.disabled = true);
          this.totalCount = 60;
          //this.getCode(); //60秒过倒计时过后才能调用的事件
          this.interval = setInterval(() => {
            this.totalCount--;
            if (this.totalCount === 0) {
              clearInterval(this.interval);
              this.totalCount = 0;
              this.disabled = false;
            }
          }, 1000);
        }
        this.sendEmailLoading = false;
      });
    },

    checkRegMsg(res) {
      if (res.data.code === -4005) {
        this.$message({
          message: "当前用户名已存在,请换另一个你喜欢的用户名吧",
          type: "warning",
        });
        return;
      }
      if (res.data.code === -4003) {
        this.$message({
          message: "用户名太短了哦!请换另一个你喜欢的用户名吧",
          type: "warning",
        });
        return;
      }
      if (res.data.code === -4004) {
        this.$message({
          message: "用户名太长了哦!请换另一个你喜欢的用户名吧,",
          type: "warning",
        });
        return;
      }

      if (res.data.code === -4001) {
        this.$message({
          message: "你的密码有点短了呢!不太安全哦,换一个长一点的密码吧",
          type: "warning",
        });
        return;
      }

      if (res.data.code === -412) {
        this.$message({
          message: "当前邮箱验证码已过期,请重新获取",
          type: "warning",
        });
        return;
      }

      if (res.data.code === -411) {
        this.$message({
          message: "验证码输入错误,请再检查一下",
          type: "warning",
        });
        return;
      }
    },
    checkSendEmailMsg(res) {
      if (res.code === -414) {
        this.$message({
          message: res.msg,
          type: "warning",
        });
      }
      if (res.code === -413) {
        this.$message({
          message: res.msg,
          type: "warning",
        });
      }
      if (res.code === -415) {
        this.$message({
          message: res.msg,
          type: "warning",
        });
      }
      if (res.code === -419) {
        this.$message({
          message: res.msg,
          type: "warning",
        });
      }
    },
  },
  computed: {
    btnText() {
      return this.totalCount !== 0
        ? `${this.totalCount}秒再次获取`
        : "获取验证码";
    },
  },
};
</script>

<style scoped lang="scss">
.form-remember {
  margin-bottom: 15px;
  text-align: right;
}
.captcha-img {
  margin-left: 10px;
}
.registry-button {
  width: 100%;
  display: block;
  font-size: 17px;
  color: #fff;
}
.space-white {
  width: 400px;
  margin-top: 10px;
  margin-left: 50%;
}

.email-item {
  display: flex;
  .email-item-btn {
    flex: 1 1 auto;
  }
}
</style>
